<template>
  <div class="app-container">
    <el-row :gutter="30">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>生日福利</span>
            <span style="font-size: small; float: right">* 说明：此处设置的生日券，将在每日上午7点自动向【全平台】当天生日的用户发放</span>
          </div>
          <div>
            <p v-if="birthdayTemp.status===0">暂未设置</p>
            <div v-else>
              <el-row :gutter="10">
                <el-col :span="3" class="col-title"><p>卡券名称：</p></el-col>
                <el-col :span="9" class="col-content">
                  <p>{{ birthdayTemp.coupon.couponName }}</p>
                </el-col>
                <el-col :span="3" class="col-title"><p>卡券类型：</p></el-col>
                <el-col :span="9" class="col-content">
                  <p><el-tag type="primary" size="mini" effect="plain">{{ couponTypeMap[birthdayTemp.type] }}</el-tag></p>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3" class="col-title"><p>展示图片：</p></el-col>
                <el-col :span="9" class="col-content">
                  <p><el-image style="max-width: 50px; max-height: 28px" :src="birthdayTemp.coupon.couponImg" :preview-src-list="[birthdayTemp.coupon.couponImg]" /></p>
                </el-col>
                <div v-if="birthdayTemp.type===1">
                  <el-col :span="3" class="col-title"><p>兑换商品：</p></el-col>
                  <el-col :span="9" class="col-content">
                    <el-popover placement="bottom" width="550" trigger="click" title="商品信息">
                      <div style="margin: 20px">
                        <el-row :gutter="20">
                          <el-col :span="5" class="col-title"><p>商品编号</p></el-col>
                          <el-col :span="7" class="col-content"><p>{{ tempProduct.productNo }}</p></el-col>
                          <el-col :span="5" class="col-title"><p>所属商城</p></el-col>
                          <el-col :span="7" class="col-content">
                            <p><el-tag type="primary" size="mini" effect="plain">{{ mallIdMap[tempProduct.mallId] }}</el-tag></p>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="5" class="col-title"><p>商品名称</p></el-col>
                          <el-col :span="7" class="col-content"><p>{{ tempProduct.productName }}</p></el-col>
                          <el-col :span="5" class="col-title"><p>运费</p></el-col>
                          <el-col :span="7" class="col-content"><p>{{ roundPrice(tempProduct.deliveryPrice) }}</p></el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="5" class="col-title"><p>规格名称</p></el-col>
                          <el-col :span="7" class="col-content"><p>{{ tempProduct.itemName }}</p></el-col>
                          <el-col :span="5" class="col-title"><p>规格属性</p></el-col>
                          <el-col :span="7" class="col-content"><p>{{ tempProduct.attributes }}: {{ tempProduct.itemAttrs }}</p></el-col>
                        </el-row>
                      </div>
                      <el-button slot="reference" size="mini" style="margin-top: 10px" @click="getProductItemVO(birthdayTemp.coupon.itemId)">查看</el-button>
                    </el-popover>
                  </el-col>
                </div>
                <div v-if="birthdayTemp.type===2">
                  <el-col :span="3" class="col-title"><p>满减规则：</p></el-col>
                  <el-col :span="9" class="col-content">
                    <p>满￥{{ roundPrice(birthdayTemp.coupon.couponCount) }}减￥{{ roundPrice(birthdayTemp.coupon.couponPrice) }}</p>
                  </el-col>
                </div>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3" class="col-title"><p>使用范围：</p></el-col>
                <el-col :span="9" class="col-content">
                  <p>{{ birthdayTemp.coupon.couponLimit }}</p>
                </el-col>
                <el-col :span="3" class="col-title"><p>有效期：</p></el-col>
                <el-col :span="9" class="col-content">
                  <p>{{ birthdayTemp.coupon.couponDuration }}天</p>
                </el-col>
              </el-row>
            </div>
            <el-button class="bottom-button" type="primary" size="medium" @click="handleModifyBirthday">设置</el-button>
            <el-button class="bottom-button" type="danger" size="medium" @click="removeBirthdayWelfare">移除</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>其他福利</span>
          </div>
          <el-table
            :key="1"
            :data="otherWelfareList"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            tooltip-effect="light"
          >
            <el-table-column label="福利名称" align="center" width="100">
              <template slot-scope="{row}">
                <span>{{ row.welfareName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="政策说明" align="center">
              <template slot-scope="{row}">
                <el-popover placement="bottom" width="550" trigger="click" title="福利政策预览">
                  <div style="margin: 20px">
                    <div v-html="row.welfarePolicy"></div>
                  </div>
                  <el-button slot="reference" size="mini">预览</el-button>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="文件下载" align="center">
              <template slot-scope="{row}">
                <el-link v-if="row.formUrl" target="_blank" :href="row.formUrl" :underline="false">
                  <el-button size="mini" circle type="primary" plain><i class="el-icon-download"></i></el-button>
                </el-link>
                <el-button v-else disabled size="mini" circle type="info" plain><i class="el-icon-download"></i></el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180px" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="{row}">
                <el-button type="primary" size="mini" @click="handleModifyOther(row)">
                  修改
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="更改生日福利设置" :visible.sync="dialogBirthdayVisible" :close-on-press-escape="false" top="80px">
      <el-radio v-for="item in couponTypeList" v-model="couponType" :label="item.key">{{ item.value }}</el-radio>
      <el-form v-show="couponType===1" ref="freeForm" :rules="freeRules" :model="freeTemp" label-width="150px" style="margin-top: 40px; width: 90%">
        <el-form-item label="兑换券名" prop="couponName">
          <el-input v-model="freeTemp.couponName" />
        </el-form-item>
        <el-form-item label="描述" prop="couponDesc">
          <el-input v-model="freeTemp.couponDesc" type="textarea" :row="2" />
        </el-form-item>
        <el-form-item label="展示图片" prop="couponImg">
          <el-input v-model="freeTemp.couponImg" placeholder="图片链接" />
          <img-upload-single @onUpload="uploadImgFree" @onRemove="removeImgFree" ref="imgUploadFree"></img-upload-single>
        </el-form-item>
        <el-form-item label="适用范围" prop="couponLimit">
          <el-input v-model="freeTemp.couponLimit" placeholder="如：限XX商品可用" />
        </el-form-item>
        <el-form-item label="商品规格编号" prop="itemId">
          <el-input v-model="freeTemp.itemId" placeholder="兑换券兑换商品的细分规格编号" style="width: 230px" />
          <el-popover placement="bottom" width="550" trigger="click" title="商品信息">
            <div style="margin: 20px">
              <el-row :gutter="20">
                <el-col :span="5" class="col-title"><p>商品编号</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ tempProduct.productNo }}</p></el-col>
                <el-col :span="5" class="col-title"><p>所属商城</p></el-col>
                <el-col :span="7" class="col-content">
                  <p><el-tag type="primary" size="mini" effect="plain">{{ mallIdMap[tempProduct.mallId] }}</el-tag></p>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="5" class="col-title"><p>商品名称</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ tempProduct.productName }}</p></el-col>
                <el-col :span="5" class="col-title"><p>运费</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ roundPrice(tempProduct.deliveryPrice) }}</p></el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="5" class="col-title"><p>规格名称</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ tempProduct.itemName }}</p></el-col>
                <el-col :span="5" class="col-title"><p>规格属性</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ tempProduct.attributes }}: {{ tempProduct.itemAttrs }}</p></el-col>
              </el-row>
            </div>
            <el-button slot="reference" @click="getProductItemVO(freeTemp.itemId)">查看商品</el-button>
          </el-popover>
        </el-form-item>
        <el-form-item label="有效天数" prop="couponDuration">
          <el-input-number v-model="freeTemp.couponDuration" :min="1" :step="1" step-strictly />
        </el-form-item>
      </el-form>
      <el-form v-show="couponType===2" ref="shopForm" :rules="shopRules" :model="shopTemp" label-width="150px" style="margin-top: 40px; width: 90%">
        <el-form-item label="兑换券名" prop="couponName">
          <el-input v-model="shopTemp.couponName" />
        </el-form-item>
        <el-form-item label="描述" prop="couponDesc">
          <el-input v-model="shopTemp.couponDesc" type="textarea" :row="2" />
        </el-form-item>
        <el-form-item label="展示图片" prop="couponImg">
          <el-input v-model="shopTemp.couponImg" placeholder="图片链接" />
          <img-upload-single @onUpload="uploadImgShop" @onRemove="removeImgShop" ref="imgUploadShop"></img-upload-single>
        </el-form-item>
        <el-form-item label="适用范围" prop="couponLimit">
          <el-input v-model="shopTemp.couponLimit" placeholder="如：限XX商品可用" />
        </el-form-item>
        <el-form-item label="满减底价" prop="couponCount">
          <el-input v-model="shopTemp.couponCount" placeholder="请填写满多少价格可使用（元）" style="width: 300px" />
        </el-form-item>
        <el-form-item label="抵扣价格" prop="couponPrice">
          <el-input v-model="shopTemp.couponPrice" placeholder="请填写可抵扣多少价格（元）" style="width: 300px" />
        </el-form-item>
        <el-form-item label="有效天数" prop="couponDuration">
          <el-input-number v-model="shopTemp.couponDuration" :min="1" :step="1" step-strictly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="couponType===1" type="primary" @click="modifyBirthdayFree">
          确认
        </el-button>
        <el-button v-if="couponType===2" type="primary" @click="modifyBirthdayShop">
          确认
        </el-button>
        <el-button @click="dialogBirthdayVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改其他福利信息" :visible.sync="dialogOtherVisible" :close-on-press-escape="false" top="80px">
      <el-form ref="otherWelfareForm" :rules="otherWelfareRules" :model="otherWelfareTemp" label-width="150px" style="width: 90%">
        <el-form-item label="表格文件" prop="formUrl">
          <el-input v-model="otherWelfareTemp.formUrl" placeholder="请上传电子表格，多个文件请放入一个压缩文件上传" style="width: 650px" />
          <file-upload-single :key="otherWelfareTemp.welfareId" ref="fileUpload" @onUpload="uploadFile" @onRemove="removeFile"></file-upload-single>
        </el-form-item>
        <el-form-item label="福利政策" prop="welfarePolicy">
          <tinymce v-if="dialogOtherVisible" v-model="otherWelfareTemp.welfarePolicy" :height="300" :width="650" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="modifyOther()">
          确认
        </el-button>
        <el-button @click="dialogOtherVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { showBirthdayWelfare, modifyBirthdayRuleFree, modifyBirthdayRuleShop, removeBirthdayWelfare, getOtherWelfareList, modifyOtherWelfare } from '@/api/welfare'
import { getProductItemVO } from '@/api/product'
import waves from '@/directive/waves'
import ImgUploadSingle from '@/components/ImgUpload/ImgUploadSingle'
import FileUploadSingle from '@/components/ImgUpload/FileUploadSingle'
import Tinymce from '@/components/Tinymce'
import { isInteger, isTwoDecimal } from '@/utils/validate'

export default {
  name: 'Coupon',
  components: { ImgUploadSingle, FileUploadSingle, Tinymce },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      birthdayTemp: {
        status: '',
        type: '',
        coupon: {}
      },
      otherWelfareList: [],
      otherWelfareTemp: {
        welfareId: undefined,
        welfarePolicy: '',
        formUrl: ''
      },
      couponType: '',
      freeTemp: {
        couponName: '',
        couponImg: '',
        couponDesc: '',
        couponLimit: '',
        itemId: '',
        couponDuration: ''
      },
      shopTemp: {
        couponName: '',
        couponImg: '',
        couponDesc: '',
        couponLimit: '',
        couponCount: '',
        couponPrice: '',
        couponDuration: ''
      },
      tempProduct: {},
      dialogBirthdayVisible: false,
      dialogOtherVisible: false,
      otherWelfareRules: {
        welfarePolicy: [{ required: true, message: '请填写福利政策说明', trigger: 'blur' }],
        formUrl: [{ required: true, message: '请上传政策表单文件', trigger: 'change' }]
      },
      freeRules: {
        couponName: [{ required: true, message: '请填写优惠券名', trigger: 'blur' }],
        couponImg: [{ required: true, message: '请上传优惠券展示图片', trigger: 'change' }],
        couponDesc: [{ required: true, message: '请填写优惠券描述', trigger: 'blur' }],
        couponLimit: [{ required: true, message: '请填写优惠券使用范围', trigger: 'blur' }],
        itemId: [{ required: true, message: '请填写兑换券兑换的商品细分规格编号', trigger: 'blur' }],
        couponDuration: [{ required: true, message: '请设置优惠券有效时长（天）', trigger: 'blur' }, { validator: isInteger, trigger: 'blur' }]
      },
      shopRules: {
        couponName: [{ required: true, message: '请填写优惠券名', trigger: 'blur' }],
        couponImg: [{ required: true, message: '请上传优惠券展示图片', trigger: 'change' }],
        couponDesc: [{ required: true, message: '请填写优惠券描述', trigger: 'blur' }],
        couponLimit: [{ required: true, message: '请填写优惠券使用范围', trigger: 'blur' }],
        couponDuration: [{ required: true, message: '请设置优惠券有效时长（天）', trigger: 'blur' }, { validator: isInteger, trigger: 'blur' }],
        couponPrice: [{ required: true, message: '请设置优惠券满多少价格可用', trigger: 'blur' }, { validator: isTwoDecimal, trigger: 'blur' }],
        couponCount: [{ required: true, message: '请设置优惠券抵扣金额', trigger: 'blur' }, { validator: isTwoDecimal, trigger: 'blur' }]
      },
      subTypeList: [
        { key: 0, value: '年节福利' },
        { key: 1, value: '生日福利' },
        { key: 3, value: '观光旅游' },
        { key: 4, value: '战时慰问' }
      ],
      subTypeMap: {
        0: '年节福利',
        1: '生日福利',
        3: '观光旅游',
        4: '战时慰问'
      },
      couponRangeList: [
        { key: 0, value: '所有成员' },
        { key: 1, value: '民警' },
        { key: 2, value: '辅警' },
        { key: 3, value: '选择用户' }
      ],
      couponRangeMap: {
        0: '所有成员',
        1: '民警',
        2: '辅警',
        3: '选择用户'
      },
      mallIdMap: {
        1: '爱心帮扶',
        2: '特价商城',
        3: '积分商城'
      },
      couponTypeList: [
        { key: 1, value: '商品兑换券' },
        { key: 2, value: '实体店满减券' }
      ],
      couponTypeMap: {
        1: '商品兑换券',
        2: '实体店满减券'
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.showBirthdayWelfare()
      this.getOtherWelfareList()
    },
    showBirthdayWelfare() {
      showBirthdayWelfare().then(response => {
        if (response.code === 0) {
          this.birthdayTemp = Object.assign({}, response.data)
        }
      })
    },
    getOtherWelfareList() {
      getOtherWelfareList().then(response => {
        if (response.code === 0) {
          this.otherWelfareList = response.data
        }
      })
    },
    resetFreeDialog() {
      this.freeTemp = {
        couponName: '',
        couponImg: '',
        couponDesc: '',
        couponLimit: '',
        itemId: '',
        couponDuration: ''
      }
    },
    resetShopDialog() {
      this.shopTemp = {
        couponName: '',
        couponImg: '',
        couponDesc: '',
        couponLimit: '',
        couponCount: '',
        couponPrice: '',
        couponDuration: ''
      }
    },
    handleModifyBirthday() {
      this.resetFreeDialog()
      this.resetShopDialog()
      this.dialogBirthdayVisible = true
      this.$nextTick(() => {
        this.$refs['freeForm'].clearValidate()
        this.$refs['shopForm'].clearValidate()
      })
    },
    modifyBirthdayFree() {
      this.$refs['freeForm'].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.freeTemp)
          modifyBirthdayRuleFree(data).then(response => {
            if (response.code === 0) {
              this.$notify({
                title: 'Success',
                message: '生日福利设置成功',
                type: 'success',
                duration: 2000
              })
              this.dialogBirthdayVisible = false
              this.showBirthdayWelfare()
            }
          })
        }
      })
    },
    modifyBirthdayShop() {
      this.$refs['shopForm'].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.shopTemp)
          data.couponPrice = data.couponPrice * 100
          data.couponCount = data.couponCount * 100
          modifyBirthdayRuleShop(data).then(response => {
            if (response.code === 0) {
              this.$notify({
                title: 'Success',
                message: '生日福利设置成功',
                type: 'success',
                duration: 2000
              })
              this.dialogBirthdayVisible = false
              this.showBirthdayWelfare()
            }
          })
        }
      })
    },
    removeBirthdayWelfare() {
      removeBirthdayWelfare().then(response => {
        if (response.code === 0) {
          this.$notify({
            title: 'Success',
            message: '移除成功',
            type: 'success',
            duration: 2000
          })
          this.showBirthdayWelfare()
        }
      })
    },
    handleModifyOther(row) {
      this.otherWelfareTemp = Object.assign({}, row)
      this.dialogOtherVisible = true
      this.$nextTick(() => {
        this.$refs['otherWelfareForm'].clearValidate()
      })
    },
    modifyOther() {
      this.$refs['otherWelfareForm'].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.otherWelfareTemp)
          modifyOtherWelfare(data).then(response => {
            if (response.code === 0) {
              this.$notify({
                title: 'Success',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.dialogOtherVisible = false
              this.getOtherWelfareList()
            }
          })
        }
      })
    },
    roundPrice(price) {
      return (price / 100).toFixed(2)
    },
    removeImgFree() {
      this.freeTemp.couponImg = ''
    },
    uploadImgFree() {
      this.freeTemp.couponImg = this.$refs.imgUploadFree.url
    },
    removeImgShop() {
      this.shopTemp.couponImg = ''
    },
    uploadImgShop() {
      this.shopTemp.couponImg = this.$refs.imgUploadShop.url
    },
    removeFile() {
      this.otherWelfareTemp.formUrl = ''
    },
    uploadFile() {
      this.otherWelfareTemp.formUrl = this.$refs.fileUpload.url
    },
    getProductItemVO(itemId) {
      this.tempProduct = {}
      getProductItemVO({ itemId: itemId }).then(response => {
        this.tempProduct = Object.assign({}, response.data)
      })
    }
  }
}
</script>

<style>
  .el-transfer-panel{
    width: 220px;
    height: 400px;
  }
  .el-transfer-panel__list.is-filterable{
    height: 400px;
  }
  .col-title {
    text-align: right
  }

  .col-title p {
    font-weight: bolder;
  }

  .col-content p {
    color: #848383
  }

  .bottom-button {
    float: right;
    margin: 25px 10px;
  }
</style>
